
use anyhow::Result;

use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use std::borrow::Borrow;

use std::ops::Sub;
use sqlx::{Pool, MySql, types};
use chrono;

use crate::miner::{JsonRpcResponse, JsonRpcError};
use crate::miner;
use crate::db;
use crate::miner::types::TaskType;
use crate::miner::jobs::SealWork;
use crate::db::SealTaskDetail;

pub async fn correct_sector_table_by_jobs(pool: &Pool<MySql>, client: &Client<HttpConnector>, url: &str, token: &str) -> Result<()> {
    let jobs = miner::jobs::query_jobs_from_miner(client, url, token).await?;
    if let Some(e) = jobs.error {
        log::info!("got error when query jobs, {:?}", e)
    }else{
        if let Some(worker_jobs) = jobs.result {
            for (worker, jobs) in worker_jobs{
                for job in jobs {
                    if job.task.eq(&TaskType::PreCommit1) || job.task.eq(&TaskType::PreCommit2) || job.task.eq(&TaskType::Commit1) {
                        let ret = db::update_worker_id_of_sector_table(pool, worker.as_str(), job.sector.number, job.task).await?;
                        println!("worker {}, sector {}, rows {}", worker, job.sector.number, ret);
                    }
                }
            }
        }
    }
    Ok(())
}

pub async fn correct_remove_sector_state(pool: &Pool<MySql>, client: &Client<HttpConnector>, url: &str, token: &str) -> Result<()> {
    let vec = db::query_p1_sector_list(pool).await?;
    for v in vec{
        let status = miner::sector::query_sector_status(client, url, token, (v.sector_number) as u64).await?;
        if let Some(e) = status.error{
            log::error!("query sector status error. sector {}, error {:?}", v.sector_number, e);
        } else {
            if let Some(status) = status.result {
                log::info!("sector {}, state {}", v.sector_number, status.state);
                if status.state.eq("Removing") || status.state.eq("Removed") {
                    log::info!("yes")
                }
            }
        }
    }
    Ok(())
}